namespace ClassyBlog.Web
{
    using System;
    using System.Web.Mvc;

    using ExtensionMethods;
    using Infrastructure;

    public static class AssetHelper
    {
        public static string StyleSheet(
            this UrlHelper instance, string fileNameWithoutExtension)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            var debugMode = instance.RequestContext
                                    .HttpContext
                                    .IsDebuggingEnabled;

            var url = instance.Content(
                Link(
                debugMode,
                Path("stylesheets"),
                fileNameWithoutExtension,
                "css"));

            return url;
        }

        public static string JavaScript(
            this UrlHelper instance, string fileNameWithoutExtension)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            var debugMode = instance.RequestContext
                                    .HttpContext
                                    .IsDebuggingEnabled;

            var url = instance.Content(
                Link(
                debugMode,
                Path("javascripts"),
                fileNameWithoutExtension,
                "js"));

            return url;
        }

        public static string Image(this UrlHelper instance, string file)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            var url = instance.Content("{0}{1}".Interpolate(
                Path("images"), file));

            return url;
        }

        private static string AssetRoot()
        {
            var root = "~/views/{0}/assets".Interpolate(
                DependencyResolver.Current
                                  .GetService<ICurrentBlogProvider>()
                                  .Current
                                  .Theme);

            return root;
        }

        private static string Path(string relativePath)
        {
            var path = "{0}/{1}".Interpolate(AssetRoot(), relativePath) + "/";

            return path;
        }

        private static string Link(
            bool debug, string path, string baseName, string fileType)
        {
            var link = path +
                       baseName +
                       "." +
                       (debug ? fileType : "min." + fileType);

            return link;
        }
    }
}